<?php

namespace app\erp\model;

use app\jun\controller\Api;
use think\Cache;
use think\Db;
use think\Model;

class Auditdb extends Model
{
    protected $pk = 'audit_id';
    protected $name = 'audit';
    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i',
        'update_time' => 'timestamp:Y-m-d H:i',
        'audit_time' => 'timestamp:Y-m-d H:i'
    ];
    protected $insert = [
        'audit_state' => 1
    ];
    protected $autoWriteTimestamp = true;
    public $param = array();
    protected $append = ['market_price'];

    public function admins()
    {
        return $this->belongsTo('Memberdb', 'audit_admin_id');
    }

    public function getMarketPriceAttr($value, $row)
    {
        $price = Db::name('sale_price')->where('goods_sku', $row['audit_sign'])->value('market_price');
        return $price;
    }

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }


    public function scopeAuditSign($query, $audit_sign)
    {
        $query->where('audit_sign', 'like', '%' . $audit_sign . '%');
    }

    public function scopeAuditState($query, $audit_state)
    {
        $query->where('audit_state', $audit_state);
    }

    public function scopeAuditMethod($query, $audit_method)
    {
        $query->where('audit_method', $audit_method);
    }

    public function scopeAuditId($query, $audit_id)
    {
        $query->where('audit_id', $audit_id);
    }

    // 基础查询
    public function base($query)
    {
        if (isset ($this->param ['audit_sign']) && $this->param ['audit_sign']) {
            $query->auditSign($this->param ['audit_sign']);
        }
        if (isset ($this->param ['audit_state']) && $this->param ['audit_state']) {
            $query->auditState($this->param ['audit_state']);
        }
        if (isset ($this->param ['audit_method']) && $this->param ['audit_method']) {
            $query->auditMethod($this->param ['audit_method']);
        }
        if (isset ($this->param ['susername']) && $this->param ['susername']) {
            $query->susername($this->param ['susername']);
        }
        if (isset ($this->param ['rusername']) && $this->param ['rusername']) {
            $query->rusername($this->param ['rusername']);
        }
        if (isset ($this->param ['create_time_start']) && $this->param ['create_time_start']) {
            $query->createTimeStart($this->param ['create_time_start']);
        }
        if (isset ($this->param ['create_time_end']) && $this->param ['create_time_end']) {
            $query->createTimeEnd($this->param ['create_time_end']);
        }
        if (isset($this->param['audit_member']) && $this->param['audit_member']) {
            $query->whereIn("audit_admin_id", Memberdb::whereLike('realname', '%' . $this->param['audit_member'] . '%')->column('member_id'));
        }
        if (isset ($this->param ['audit_id']) && $this->param ['audit_id']) {
            $query->auditId($this->param ['audit_id']);
        }
        if (isset ($this->param ['audit_type']) && $this->param ['audit_type']) {
            $query->auditType($this->param ['audit_type']);
        }
    }

    public function scopeAuditType($query, $audit_type)
    {
        $query->where('audit_type', $audit_type);
    }

    public function scopeCreateTimeStart($query, $create_time)
    {
        $query->whereTime('create_time', '>=', $create_time);
    }

    public function scopeCreateTimeEnd($query, $create_time)
    {
        $time = strtotime($create_time);
        $date = strtotime('+1 day', $time);
        $query->whereTime('create_time', '<', $date);
    }

    public function scopeSusername($query, $susername)
    {
        $memberdb = new Memberdb ();
        $get_supplier_id = $memberdb->useGlobalScope(false)->where('supplier_name', 'like', '%' . $susername . '%')->where('is_supplier', 1)->select();
        if (!$get_supplier_id->isEmpty()) {
            $member_ids = array();
            $get_supplier_id = $get_supplier_id->toArray();
            foreach ($get_supplier_id as $key => $val) {
                array_push($member_ids, $val ['member_id']);
            }
            $query->where('supplier_id', 'IN', $member_ids);
        } else {
            $query->where('supplier_id', -1);
        }
    }

    public function scopeRusername($query, $rusername)
    {
        $memberdb = new Memberdb ();
        $get_supplier_id = $memberdb->useGlobalScope(false)->where('realname', 'like', '%' . $rusername . '%')->where('is_supplier', 1)->select();
        if (!$get_supplier_id->isEmpty()) {
            $member_ids = array();
            $get_supplier_id = $get_supplier_id->toArray();
            foreach ($get_supplier_id as $key => $val) {
                array_push($member_ids, $val ['member_id']);
            }
            $query->where('supplier_id', 'IN', $member_ids);
        } else {
            $query->where('supplier_id', -1);
        }
    }

    public function ajaxSave()
    {
        // 比较数据差异化
        $before_option = $this->param ['before_option'];
        $after_option = $this->param ['after_option'];
        $before_arr = array();
        $after_arr = array();
        if ($this->param ['audit_method'] == 3) {
            // 移除非验证标识 这里针对产品
            unset ($before_option ['update_time']);
            unset ($before_option ['sale_attr']);
            unset ($before_option ['sale_price_info']);
            unset ($before_option ['audit_state']);
            unset ($before_option ['is_copy']);

            foreach ($before_option as $key => $val) {
                if (array_key_exists($key, $after_option)) {
                    if ($val != $after_option [$key]) {
                        array_push($before_arr, array(
                            'field' => $key,
                            'value' => $val
                        ));
                        array_push($after_arr, array(
                            'field' => $key,
                            'value' => $after_option [$key]
                        ));
                    }
                } else {
                    array_push($before_arr, array(
                        'field' => $key,
                        'value' => $val
                    ));
                    array_push($after_arr, array(
                        'field' => $key,
                        'value' => ''
                    ));
                }
            }
        }
        $this->param ['before_option'] = json_encode($before_arr);
        $this->param ['after_option'] = json_encode($after_arr);
        if (count($before_arr) != 0 || $this->param ['audit_method'] != 3) {
            $this->allowField(true)->save($this->param);
            return 'success';
        } else {
            return 'fail';
        }
    }

    public function ajaxSaveAll()
    {
        // 比较数据差异化
        foreach ($this->param as $k => $v) {
            $before_option = $this->param [$k] ['before_option'];
            $after_option = $this->param [$k] ['after_option'];
            $before_arr = array();
            $after_arr = array();
            if ($this->param [$k] ['audit_method'] == 3) {
                // 移除非验证标识 这里针对产品
                unset ($before_option ['update_time']);
                unset ($before_option ['sale_attr']);
                unset ($before_option ['sale_price_info']);
                unset ($before_option ['audit_state']);
                unset ($before_option ['is_copy']);

                foreach ($before_option as $key => $val) {
                    if (array_key_exists($key, $after_option)) {
                        if ($val != $after_option [$key]) {
                            array_push($before_arr, array(
                                'field' => $key,
                                'value' => $val
                            ));
                            array_push($after_arr, array(
                                'field' => $key,
                                'value' => $after_option [$key]
                            ));
                        }
                    } else {
                        array_push($before_arr, array(
                            'field' => $key,
                            'value' => $val
                        ));
                        array_push($after_arr, array(
                            'field' => $key,
                            'value' => ''
                        ));
                    }
                }
            }
            $this->param [$k] ['before_option'] = json_encode($before_arr);
            $this->param [$k] ['after_option'] = json_encode($after_arr);
        }
        $data = $this->saveAll($this->param);
        return 'success';
    }

    public function ajaxSelect()
    {
        $return ['data'] = $this->ajaxList();
        $return ['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxList()
    {
        $data = $this->order('audit_state asc,audit_id desc')->page($this->param ['page'], $this->param ['limit'])->select();
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data [$key] = $this->handleData($val);
            }
        }
        return $data;
    }

    public function ajaxFind()
    {
        $data = $this->find();
        $data = $data->toArray();
        return $data;
    }

    public function ajaxCount()
    {
        $count = $this->count();
        return $count;
    }

    protected function handleData($val)
    {
        foreach ($val as $k => $v) {
            $val [$k] = $v;
            switch ($k) {
                case 'audit_admin_id':
                    if ($v) {
                        $memberdb = new Memberdb ();
                        $memberdb->param ['member_id'] = $v;
                        $get_admin = $memberdb->useGlobalScope(false)->where('member_id', $v)->find();
                        $val ['audit_admin_name'] = '';
                        if ($get_admin) {
                            $get_admin = $get_admin->toArray();
                            $val ['audit_admin_name'] = $get_admin ['username'];
                        }
                    }
                    break;
                case 'supplier_id' :
                    $val ['supplier_name'] = '';
                    $val ['realname'] = '';
                    if ($v) {
                        $memberdb = new Memberdb ();
                        $get_member = $memberdb->useGlobalScope(false)->where('member_id', $v)->find();
                        if ($get_member) {
                            $val ['supplier_name'] = $get_member ['supplier_name'];
                            $val ['realname'] = $get_member ['realname'];
                        }
                    }
                    break;
                case 'audit_method' :
                    $audit_method = array(
                        '1' => '分类',
                        '2' => '品牌',
                        '3' => '产品'
                    );
                    $val [$k] = $audit_method [$v];
                    break;
                case 'audit_type' :
                    $audit_type = array(
                        '1' => '新增',
                        '2' => '修改'
                    );
                    $val [$k] = $audit_type [$v];
                    break;
                default :
                    break;
            }
            $before_option = json_decode($val ['before_option'], true);
            $after_option = json_decode($val ['after_option'], true);
            $view_text = '';
            if ($val ['audit_type'] == '修改' && is_array($before_option)) {
                for ($i = 0; $i < count($before_option); $i++) {
                    if (is_array($before_option [$i] ['value'])) {
                        $view_text .= $before_option [$i] ['field'] . '：内容有修改；';
                    } else {
                        if ($before_option [$i] ['field'] == 'goods_content') {
                            $view_text .= $before_option [$i] ['field'] . '：内容有修改；';
                        } else {
                            $view_text .= $before_option [$i] ['field'] . '：' . $before_option [$i] ['value'] . '(<font>' . $after_option [$i] ['value'] . '</font>)；';
                        }
                    }
                }

            } else {
                $view_text = '新增内容';
            }
            $val ['view_text'] = $view_text;
        }
        return $val;
    }

    public function pass()
    {
        $this->save([
            'audit_state' => 2,
            'audit_admin_id' => MEMBER_ID,
            'audit_time' => time()
        ], [
            'audit_id' => $this->param ['audit_id']
        ]);
        $data = $this->where('audit_id', $this->param ['audit_id'])->find()->toArray();
        if ($data ['audit_method'] == 3) {
            // 验证消息是否有通知
            $post_noticedb = new PostNoticedb ();
            $post_noticedb->param ['sku_order_no'] = $data ['audit_sign'];
            $post_noticedb->param ['site_id'] = 117;
            $post_noticedb->save(array(
                'is_audit' => 1
            ), array(
                'sku_order_no' => $data ['audit_sign'],
                'site_id' => 117
            ));
        }
        $this->chkState($this->param ['audit_id']);
    }

    public function refuse()
    {
        $this->save([
            'audit_state' => 3,
            'remark' => $this->param['remark'],
            'audit_admin_id' => MEMBER_ID,
            'audit_time' => time()
        ], [
            'audit_id' => $this->param ['audit_id']
        ]);

        // 数据回滚
        $this->dataCallBack($this->param ['audit_id']);
        $this->chkState($this->param ['audit_id']);
    }

    protected function dataCallBack($audit_id)
    {
        $get_audit_sign = $this->where('audit_id', $audit_id)->find()->toArray();
        if ($get_audit_sign ['audit_type'] == 1) {
            if ($get_audit_sign['audit_method'] == 3) {
                Goodsdb::where('goods_sku', $get_audit_sign['audit_sign'])
                    ->update(['is_audit' => 'no', 'audit_remark' => $get_audit_sign['remark']]);
            }
            return 'false';
        }
        switch ($get_audit_sign ['audit_method']) {
            case '1' :
                $categorydb = new Categorydb ();
                break;
            case '2' :
                $branddb = new Branddb ();
                break;
            case '3' :
                $goodsdb = new Goodsdb ();
                $goodsdb->param = $get_audit_sign ['old_option'];
                $old_option = json_decode($get_audit_sign ['old_option'], true);
                unset ($old_option ['create_time']);
                unset ($old_option ['update_time']);
                $goods_pictures = $old_option ['goods_pictures'];
                unset ($old_option ['goods_picture']);
                unset ($old_option ['goods_pictures']);
                unset ($old_option ['delete_time']);
                $new_pictures = array();
                if ($goods_pictures) {
                    for ($i = 0; $i < count($goods_pictures); $i++) {
                        array_push($new_pictures, $goods_pictures [$i] ['upload_id']);
                    }
                    if ($new_pictures) {
                        $old_option ['goods_pictures'] = implode(',', $new_pictures);
                    }
                }
                foreach ($old_option as $key => $val) {
                    if ($val === false) {
                        $old_option [$key] = 0;
                    }
                    if ($val === true) {
                        $old_option [$key] = 0;
                    }
                }
                if (count($old_option ['sale_attr']) > 0) {
                    $new_sale_attr = array();
                    for ($i = 0; $i < count($old_option ['sale_attr']); $i++) {
                        array_push($new_sale_attr, $old_option ['sale_attr'] [$i]);
                    }
                    unset ($old_option ['sale_attr']);
                    $old_option ['sale_attr'] = $new_sale_attr;
                } else {
                    unset ($old_option ['sale_attr']);
                }
                $attr_value = $old_option ['attr_value'];
                unset ($old_option ['attr_value']);
                foreach ($attr_value as $key => $val) {
                    $old_option [$key] = $val;
                }
                $sale_price_info = $old_option ['sale_price_info'] ['data'];
                unset ($old_option ['sale_price_info']);
                $sale_attr_price_name = array();
                $market_price = array();
                $sale_price = array();
                $api_price = array();
                $give_score = array();
                $view_stock = array();
                foreach ($sale_price_info as $key => $val) {
                    array_push($sale_attr_price_name, $val ['sale_attr_price_name']);
                    array_push($market_price, $val ['market_price']);
                    array_push($sale_price, $val ['sale_price']);
                    array_push($api_price, $val ['api_price']);
                    array_push($give_score, $val ['give_score']);
                    array_push($view_stock, $val ['view_stock']);
                }
                $old_option ['sale_attr_price_name'] = $sale_attr_price_name;
                $old_option ['market_price'] = $market_price;
                $old_option ['sale_price'] = $sale_price;
                $old_option ['api_price'] = $api_price;
                $old_option ['give_score'] = $give_score;
                $old_option ['view_stock'] = $view_stock;
                $old_option ['sale_state'] = 2;
                $old_option ['audit_remark'] = $get_audit_sign['remark'];
                $goodsdb->param = $old_option;
                $goodsdb->param ['audit_remark'] = $get_audit_sign['remark'];
                $goodsdb->param ['is_audit'] = 'no';
                $goodsdb->ajaxSave();
                // 写通知
                $postNoticedb = new PostNoticedb ();
                $postNoticedb->param ['post_type'] = 4;
                $postNoticedb->param ['sku_order_no'] = $get_audit_sign ['audit_sign'];
                $postNoticedb->param ['old_data'] = 1;
                $postNoticedb->param ['new_data'] = 2;
                $postNoticedb->param ['is_audit'] = 2;
                $postNoticedb->ajaxSave();
                break;
            default :
                break;
        }
    }

    protected function junPush($goods_sku)
    {
        // 军采 如果审核通过 推送商品
        $goodsdb = new Goodsdb ();
        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $goods_sku)->find();
        $post_json = array();
        if ($get_goods) {
            $get_goods = $get_goods->toArray();
            if ($get_goods['jun_update']) {
                $temp ['sku'] = $goods_sku;
                $temp ['updateType'] = $get_goods['jun_update'];
                array_push($post_json, $temp);
            } else {
                if ($get_goods ['is_push'] == 1) {
                    // 修改
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 2;
                    array_push($post_json, $temp);
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 3;
                    array_push($post_json, $temp);
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 4;
                    array_push($post_json, $temp);
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 5;
                    array_push($post_json, $temp);
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 6;
                    array_push($post_json, $temp);
                } else {
                    $goodsdb->where('goods_sku', $goods_sku)->update(['is_push' => 1]);
                    $temp ['sku'] = $goods_sku;
                    $temp ['updateType'] = 1;
                    array_push($post_json, $temp);
                }
            }
        }
        $jun_api = new Api ();
        $return_json = $jun_api->ajaxproductupdateinfo($post_json);
        $junapidb = new Junapidb ();
        $junapidb->param ['goods_sku'] = $temp ['sku'];
        $junapidb->param ['send_json'] = $post_json;
        $junapidb->param ['result_json'] = $return_json;
        $junapidb->ajaxSave();
    }

    protected function chkState($audit_id)
    {
        $get_audit_sign = $this->useGlobalScope(false)->where('audit_id', $audit_id)->find()->toArray();
        if ($get_audit_sign ['audit_type'] == 1) {
            switch ($get_audit_sign ['audit_method']) {
                case '1' :
                    $categorydb = new Categorydb ();
                    $categorydb->param ['category_sign'] = $get_audit_sign ['audit_sign'];
                    $categorydb->param ['audit_state'] = $get_audit_sign ['audit_state'] == 2 ? 1 : -1;
                    $categorydb->ajaxSave();
                    break;
                case '2' :
                    $branddb = new Branddb ();
                    $where ['brand_sign'] = $get_audit_sign ['audit_sign'];
                    $data ['audit_state'] = $get_audit_sign ['audit_state'] == 2 ? 1 : -1;
                    $branddb->ajaxSaveOne($data, $where);
                    break;
                case '3' :
                    $goodsdb = new Goodsdb ();
                    $goodsdb->param ['goods_sku'] = $get_audit_sign ['audit_sign'];
                    $goodsdb->ajaxSaveOne('audit_state', $get_audit_sign ['audit_state'] == 2 ? 1 : -1);
                    // 军采 如果审核通过 推送商品
                    if (SITE_ID == 117 && $get_audit_sign['audit_state'] == 2) {
                        $this->junPush($get_audit_sign ['audit_sign']);
                    }
                    break;
                default :
                    break;
            }
        } else {
            $data_count = $this->master()->where('audit_sign', $get_audit_sign ['audit_sign'])->where('audit_state', 1)->count();
            if ($data_count == 0) {
                switch ($get_audit_sign ['audit_method']) {
                    case '1' :
                    case '2' :
                    case '3' :
                        $goodsdb = new Goodsdb ();
                        $goodsdb->param ['goods_sku'] = $get_audit_sign ['audit_sign'];
                        $old_option = json_decode($get_audit_sign ['old_option'], true);
                        $goodsdb->ajaxSaveOne('audit_state', $get_audit_sign ['audit_state'] == 2 ? 1 : -1);
                        // 军采 如果审核通过 推送商品
                        if (SITE_ID == 117 && $get_audit_sign['audit_state'] == 2) {
                            $this->junPush($get_audit_sign ['audit_sign']);
                        }
                        break;
                    default :
                        break;
                }
            }
        }
        Cache::clear('goods');
        Cache::clear('sale_price');
    }
}